library(groundhog)
groundhog.library('taRifx', '2023-04-22')
library(ggplot2)
library(dplyr)
library(reshape2)
library(fst)
library(haven)
library(miceadds)
library(taRifx)

load("main_data.rdata")

# create bars per year for local elections  

inc_1985 <- 
  read.fst("ind1985.fst")

inc_1986 <- 
  read.fst("ind1986.fst")

inc_1987 <- 
  read.fst("ind1987.fst")

bef_father <-
  read.fst("bef1986.fst") %>% 
  select("PNR", "KOEN", "ALDER")

# Average over income 1985-1987

inc <- 
  left_join(inc_1985 %>% select(c("PNR", "SAMLINK_NY")), 
            inc_1986 %>% select(c("PNR", "SAMLINK_NY")), 
            by = "PNR") %>% 
  left_join(., inc_1987 %>% select(c("PNR", "SAMLINK_NY")),
            by = "PNR") %>% 
  mutate(SAMLINK_NY = rowMeans(cbind(SAMLINK_NY.x, SAMLINK_NY.y, SAMLINK_NY), na.rm = TRUE)) %>% 
  select(c("PNR", SAMLINK_NY))

inc <- 
  left_join(inc, bef_father, by = "PNR")

inc <-
  inc %>%
  filter(KOEN == 1 & ALDER > 17) %>% 
  group_by(KOEN, ALDER) %>% 
  mutate(inc_tile = ntile(SAMLINK_NY, 20)) 

# make vector of continuing municipalities: 

kom_cont <- 
  c("101", "147", "151", "153", "155", "157", "159", "161", 
    "163", "165", "167", "169", "173", "175", "183", "185", 
    "187", "201", "217", "223", "400", "253", "269", "329", 
    "461", "563", "607", "727", "741", "751", "773", "825")

var <- c("run_kv", "elected_kv")
lab <- c("Running for \nmunicipality", 
         "Elected for \nmunicipality")

data_out <- data_frame()
data_model <- data_frame()

for(k in seq(1993, 2013, by = 4)){
  for(j in 1:2){
    
    bef <- 
      read.fst(paste(work_data, "grunddata/", "bef", k, ".fst", sep = "")) %>% 
      select("PNR", "FAR_ID", "KOM")
    
    data_year <- 
      data_comp %>% 
      filter(four_years == k) %>% 
      filter(.[,paste(var[j],"_", k, sep = "")] == 1) %>% 
      left_join(., bef, by = "PNR") %>% 
      left_join(., inc, by = c("FAR_ID" = "PNR"))
    
    
    data_merg <- 
      data_year %>% 
      filter(!KOM %in% kom_cont & !is.na(inc_tile)) %>% 
      mutate(inc_tile = inc_tile / 20 - 0.025)
    
    data_cont <- 
      data_year %>% 
      filter(KOM %in% kom_cont & !is.na(inc_tile)) %>% 
      mutate(inc_tile = inc_tile / 20 - 0.025)
    
    data_out_temp <-
      data_frame(year = k,
                 lab  = lab[j],
                 mean_merg  = mean(data_merg$inc_tile),
                 mean_cont  = mean(data_cont$inc_tile),
                 std_merg   = sd(data_merg$inc_tile)/sqrt(length(data_merg$inc_tile)),
                 std_cont   = sd(data_cont$inc_tile)/sqrt(length(data_cont$inc_tile)),
                 n_merg_kom = length(data_merg$inc_tile),
                 n_cont_kom = length(data_cont$inc_tile))
    
    data_out <- 
      bind_rows(data_out, data_out_temp)
    
    data_year_out <- 
      bind_rows(data_merg %>% 
                  select(c("PNR", "inc_tile", "KOM")) %>% 
                  mutate(year = k,
                         type = var[j], 
                         merg = 1),
                data_cont %>% 
                  select(c("PNR", "inc_tile", "KOM")) %>% 
                  mutate(year = k,
                         type = var[j], 
                         merg = 0))
    data_model <- 
      bind_rows(data_model, data_year_out)
  }
  print(k)
  print(Sys.time())
}

data_plot <- 
  melt(as.data.frame(data_out), 
       id = c("year", "lab"))

data_points <- 
  data_plot %>% 
  filter(variable == "mean_merg" | 
           variable == "mean_cont") %>% 
  mutate(estimate = value,
         variable = case_when(variable == "mean_merg" ~ "merg",
                              variable == "mean_cont" ~ "cont"))  %>%
  select(c("year", "lab", "variable", "estimate"))


data_ses <- 
  data_plot %>% 
  filter(variable == "std_merg" | 
           variable == "std_cont") %>% 
  mutate(se = value,
         variable = case_when(variable == "std_merg" ~ "merg",
                              variable == "std_cont" ~ "cont"))  %>%
  select(c("year", "lab", "variable", "se")) 

plot_data <- 
  left_join(data_points, data_ses) %>% 
  mutate(year = ifelse(variable == "merg", year - 0.2, year + 0.2))

plot_data <- 
  plot_data %>% 
  mutate(lab = as.factor(lab),
         lab = factor(lab, levels = levels(lab)[c(2,1)]))

plot <- 
  ggplot(data = plot_data,
         aes(x = year,
             y = estimate,
             ymin = estimate + qnorm(0.025) * se,
             ymax = estimate + qnorm(0.975) * se,
             alpha = variable)) + 
  facet_grid(lab ~ .) +
  geom_errorbar(width = 0) + 
  geom_point() + 
  theme_classic() +
  scale_y_continuous("Father's income percentilie") + 
  scale_x_continuous("Year", breaks = seq(1993, 2013, 4)) +
  geom_vline(xintercept = 2003, linetype = "dashed", alpha = 0.5) + 
  scale_alpha_discrete("", range = c(0.25, 1), 
                       labels = c("Continuing \nmunicipalities",
                                  "Amalgamated \nmunicipalities"))  +
  theme(panel.spacing = unit(2, "lines"))

# Find model estimates: 

ests_elected <- matrix(NA, nrow = 5, ncol = 4)
ests_running <- matrix(NA, nrow = 5, ncol = 4)

for(i in 1:4){
  k <- seq(2001, 2013, 4)[i]
  
  data_mod_elected <- 
    data_model %>% 
    filter((year == k - 8 | year == k) & type == "elected_kv") %>% 
    mutate(post = year == k)
  
  mod_elected <- lm.cluster(formula = inc_tile ~ post*merg + as.factor(KOM), 
                            data = data_mod_elected, 
                            cluster = data_mod_elected$PNR)
  
  ests_elected[1:2, i] <- summary(mod_elected)[nrow(summary(mod_elected)), 1:2]
  ests_elected[  4, i] <- nrow(data_mod_elected)
  ests_elected[  5, i] <- length(unique(data_mod_elected$PNR))
  
  # repeat for running
  
  data_mod_running <- 
    data_model %>% 
    filter((year == k - 8 | year == k) & type == "run_kv") %>% 
    mutate(post = year == k)
  
  mod_running <- lm.cluster(formula = inc_tile ~ post*merg + as.factor(KOM), 
                            data = data_mod_running, 
                            cluster = data_mod_running$PNR)
  
  ests_running[1:2, i] <- summary(mod_running)[nrow(summary(mod_running)), 1:2]
  ests_running[  4, i] <- nrow(data_mod_running)
  ests_running[  5, i] <- length(unique(data_mod_running$PNR))
  
}

ests_running[3, ] <- paste("[",  round(ests_running[1, ] + qnorm(0.025) * ests_running[2, ], 3),
                           "; ", round(ests_running[1, ] + qnorm(0.975) * ests_running[2, ], 3), 
                           "]", sep = "")
ests_elected[3, ] <- paste("[",  round(ests_elected[1, ] + qnorm(0.025) * ests_elected[2, ], 3),
                           "; ", round(ests_elected[1, ] + qnorm(0.975) * ests_elected[2, ], 3), 
                           "]", sep = "")

ests_elected[1:2,] <- round(destring(ests_elected[1:2,]), 3)
ests_running[1:2,] <- round(destring(ests_running[1:2,]), 3)

parent_selection_income <-
  rbind(ests_elected,
        ests_running)
